import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import _ from 'lodash';
import qs from 'qs';
import moment from 'moment';

import { addTab, timeLimit } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import PageHeader from '@/components/PageHeader';

import {
  Row,
  Col,
  Card,
  Input,
  DatePicker,
  Cascader,
  Select,
  Button,
  Table,
  message,
} from 'antd';

import ChartInfoElem from './components/ChartInfoElem';
import '@ant-design/compatible/assets/index.css';

const { RangePicker } = DatePicker;
const { Option } = Select;
const { pathname } = window.location;
const { Item } = Form;
interface WithdrawalDetailProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  loading: boolean;
  detailInfo: any;
  gardenList: any;
  partnersList: any;
  INITINFO: any;
  location: {
    query?: any;
  };
}

interface WithdrawalDetailState {
  searchValues: any;
}

function mapStateToProps(state: any) {
  const {
    withdrawalDetail: {
      detailInfo, gardenList, partnersList, loading,
    },
    common: { INITINFO },
  } = state;

  return {
    detailInfo,
    gardenList,
    partnersList,
    loading,
    INITINFO,
  };
}

@connect(mapStateToProps)
class WithdrawalDetail extends Component<WithdrawalDetailProps, WithdrawalDetailState> {
  timer: any = null;

  columns = [
    {
      title: '日期',
      dataIndex: 'stat_date',
    },
    {
      title: '快递员入账',
      dataIndex: 'courier_income',
    },
    {
      title: '取件用户入账',
      dataIndex: 'consignee_income',
    },
    {
      title: '揽/寄件入账',
      dataIndex: 'sending_income',
    },
    {
      title: '寄存入账',
      dataIndex: 'deposit_income',
    },
    {
      title: '入账总额',
      dataIndex: 'total_income',
    },
  ];

  state: WithdrawalDetailState = {
    searchValues: {},
  };

  static getDerivedStateFromProps(nextProps: any, perState: any) {
    const {
      location: { search },
    } = nextProps;
    const query = qs.parse(search, { ignoreQueryPrefix: true });
    const { ...searchValues } = query;

    return {
      ...perState,
      searchValues,
    };
  }

  componentDidMount() {
    this.setFieldsValue();
    this.fetchDeviceTypeList();
    const { detailInfo } = this.props;
    if (detailInfo?.list?.length) return;

    this.fetchAction('fetch', this.getQueryParams());
    this.fetchAction('partners', { name: '' });
    this.fetchAction('garden');
    this.fetchAction('common/fetchAddressList');
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues } = this.state;
    if (!_.isEqual(searchValues, prevState.searchValues)) {
      this.setFieldsValue();
      this.fetchAction('fetch', this.getQueryParams());
    }
  }

    // 获取设备类型
    fetchDeviceTypeList = () => {
      const { dispatch } = this.props;
      dispatch({
        type: 'common/fetchDeviceType',
        payload: {},
      });
    }

  // 表单设置初始值
  setFieldsValue = () => {
    const {
      searchValues: {
        start_date,
        end_date,
        stat_type,
        stat_unit,
        storage_code,
        momentDate,
        areaCodes,
        ...others
      },
    } = this.state;

    const params = {
      momentDate,
      areaCodes,
      stat_type,
      storage_code,
    };

    if (start_date) {
      params.momentDate = [moment(start_date), moment(end_date)];
    }
    if (others['org1.area_code']) {
      params.areaCodes = [
        others['org1.area_code'],
        others['org2.area_code'],
        others['org3.area_code'],
      ];
    }

    const { form: { setFieldsValue } } = this.props;
    setFieldsValue({
      ...params,
      garden: Number(others['garden.id']) || undefined,
      franchise: Number(others['franchise.id']) || undefined,
      stat_unit: !stat_unit ? 'day' : stat_unit,
    });
  };

  handlePartnersSearch = (name: string) => {
    clearTimeout(this.timer);

    this.timer = setTimeout(() => {
      this.fetchAction('partners', { name });
    }, 500);
  };

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFieldsAndScroll } } = this.props;
    validateFieldsAndScroll((errors, values) => {
      if (errors) return;

      const {
        franchise, garden, areaCodes, momentDate, storage_code, stat_type,
      } = values;

      if (storage_code && !stat_type) {
        message.error('输入设备编号必须选择设备类型！');
        return;
      }

      const { gardenList, partnersList } = this.props;
      const franchiseItem = partnersList.filter((item: any) => item.id === franchise);
      const gardenItem = gardenList.filter((item: any) => item.id === garden);

      const params = {
        ...values,
        'franchise.id': franchise || '',
        'franchise.name': franchiseItem[0]?.name || '',
        'garden.id': garden || '',
        'garden.name': gardenItem[0]?.name || '',
        'org1.area_code': areaCodes && areaCodes[0],
        'org2.area_code': areaCodes && areaCodes[1],
        'org3.area_code': areaCodes && areaCodes[2],
        start_date: momentDate ? moment(momentDate[0]).format('YYYY-MM-DD') : '',
        end_date: momentDate ? moment(momentDate[1]).format('YYYY-MM-DD') : '',
        pageNum: 1,
        numPerPage: 20,
      };

      delete params.franchise;
      delete params.garden;
      delete params.areaCodes;
      delete params.momentDate;

      const { dispatch } = this.props;
      addTab(dispatch, {
        name: '统计曲线',
        url: `${pathname}?${qs.stringify(params)}`,
        isTopMenu: true,
      });
    });
  };

  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { dispatch } = this.props;
    const params = {
      stat_unit: 'day',
      start_date: '',
      end_date: '',
      pageNum: 1,
      numPerPage: 20,
    };
    addTab(dispatch, {
      name: '统计曲线',
      url: `${pathname}?${qs.stringify(params)}`,
      isTopMenu: true,
    });
  };

  // 获取参数
  getQueryParams = () => {
    const { searchValues } = this.state;
    const { ...params } = searchValues;

    if (!params.start_date) params.start_date = '';
    if (!params.end_date) params.end_date = '';
    if (!params.stat_unit) params.stat_unit = 'day';

    params.pageNum = 1;
    params.numPerPage = 20;

    return params;
  };

  fetchAction = (typeName: string, payload = {}) => {
    const type = typeName.indexOf('common') >= 0 ? typeName : `withdrawalDetail/${typeName}`;

    const { dispatch } = this.props;
    dispatch({ type, payload });
  };

  render() {
    const {
      form: { getFieldDecorator },
      loading,
      detailInfo,
      partnersList,
      gardenList,
      INITINFO: { addressList, deviceType },
    } = this.props;

    const dataSource = detailInfo.list || [];

    const { searchValues } = this.state;
    const stat_unit = searchValues.stat_unit === 'day' || !searchValues.stat_unit ? '天' : '月';

    return (
      <Fragment>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          <Form hideRequiredMark onSubmit={this.handleSearch} className="tableListForm">
            <Row gutter={12}>
              <Col md={6} sm={24}>
                <Item label="起止日期" colon={false}>
                  {getFieldDecorator('momentDate')(
                    <RangePicker disabledDate={timeLimit} format="YYYY-MM-DD" />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="　省市区" colon={false}>
                  {getFieldDecorator('areaCodes')(
                    <Cascader changeOnSelect options={addressList} placeholder="请输入" />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="　　小区" colon={false}>
                  {getFieldDecorator('garden')(
                    <Select
                      showSearch
                      allowClear
                      placeholder="请选择"
                      filterOption={(input: any, option: any) => option.props.children
                        .toLowerCase().indexOf(input.toLowerCase()) >= 0
                      }
                    >
                      {gardenList
                        && gardenList.map((item: any) => (
                          <Option value={item.id} key={item.id}>
                            {item.name}
                          </Option>
                        ))}
                    </Select>,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="　合作商" colon={false}>
                  {getFieldDecorator('franchise')(
                    <Select
                      showSearch
                      allowClear
                      placeholder="请选择"
                      onSearch={this.handlePartnersSearch}
                      filterOption={(input: any, option: any) => option.props.children
                        .toLowerCase().indexOf(input.toLowerCase()) >= 0
                      }
                    >
                      {partnersList
                        && partnersList.map((item: any) => (
                          <Option value={item.id} key={item.id}>{item.name}</Option>
                        ))}
                    </Select>,
                  )}
                </Item>
              </Col>
            </Row>
            <Row gutter={12}>
              <Col md={6} sm={24}>
                <Item label="设备类型" colon={false}>
                  {getFieldDecorator('stat_type')(
                    <Select allowClear placeholder="请选择">
                      {Object.keys(deviceType).map((key:any) => (
                        <Option value={key} key={key}>
                          {deviceType[key]}
                        </Option>
                      ))}
                    </Select>,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="设备编号" colon={false}>
                  {getFieldDecorator('storage_code')(
                    <Input placeholder="请输入" />,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <Item label="统计单位" colon={false}>
                  {getFieldDecorator('stat_unit', { initialValue: 'day' })(
                    <Select placeholder="请选择">
                      <Option value="day">天</Option>
                      <Option value="month">月</Option>
                    </Select>,
                  )}
                </Item>
              </Col>
              <Col md={6} sm={24}>
                <div className="flexFeView">
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="smallButton"
                  >
                    查询
                  </Button>
                  <Button
                    type="primary"
                    className="addButton smallButton marginL16"
                    onClick={this.handleReset}
                  >
                    重置
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card bordered={false}>
          <div className="subtitle marginB12">统计单位：{stat_unit}</div>
          <ChartInfoElem chartInfo={detailInfo.chart} />
        </Card>

        <Card bordered={false} className="tableList">
          <Table
            rowKey="stat_date"
            loading={loading}
            className="statementTable"
            columns={this.columns}
            dataSource={dataSource}
            pagination={false}
          />
        </Card>

      </Fragment>
    );
  }
}

export default Form.create()(WithdrawalDetail);
